package com.polaris.live.ui.welcome

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.splashscreen.SplashScreen
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.StringUtils
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.mvvm.base2.BaseVbActivity
import com.polaris.live.common.network.getSuccessResult
import com.polaris.live.common.util.ReflexUtils
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.databinding.ActivityWelcomeBinding
import com.polaris.live.dialog.UniversalButtonDialog
import com.polaris.live.manager.AdJustManager
import com.polaris.live.manager.PageManager
import com.polaris.live.resp.back_resp.DiscontinuedExt
import com.polaris.live.resp.event.AppVersionUpdateEvent
import com.polaris.live.resp.event.FcmRouterEvent
import com.polaris.live.translation.R.string
import com.polaris.live.ui.main.activity.MainActivity
import com.polaris.live.utils.TrackHelper
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.WelcomeViewModel
import org.greenrobot.eventbus.EventBus

/**
 * 启动页
 *
 * @author Created by 半仙 on 2023/7/31/031 17:01
 */
class WelcomeActivity : BaseVbActivity<WelcomeViewModel, ActivityWelcomeBinding>() {

    //重试次数
    private var mRetryTimes = 0

    //状态监听
    private val mNetStateListener = object : NetworkUtils.OnNetworkStatusChangedListener {
        override fun onDisconnected() {
        }

        override fun onConnected(networkType: NetworkUtils.NetworkType?) {
            mRetryTimes = 0

            mViewModel.config()
        }
    }

    private var mSplashScreen: SplashScreen? = null

    override fun initImmersionBar() {
        ImmersionBar.with(this)
            .transparentBar()
            .statusBarDarkFont(true)
            .navigationBarDarkIcon(true)
            .init()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        //这个莫名其妙解决了起屏页大小的问题，为什么？？？
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        // Handle the splash screen transition.
        mSplashScreen = installSplashScreen()

        super.onCreate(savedInstanceState)

        //一直停留在SplashScreen启动界面
        keepScreen(true)
    }

    override fun initView(savedInstanceState: Bundle?) {
        if (isMainTaskRunning()) {
            finish()
            return
        }

        TrackHelper.postTrack(
            this,
            TrackEventConst.EVENT_WELCOME_UV,
            TrackEventConst.TRACK_PAGE
        )

        NetworkUtils.registerNetworkStatusChangedListener(mNetStateListener)

        initData()
    }

    private fun initData() {
        mRetryTimes = 0

        if (PageManager.isOpenMain()) {
            ViewUtils.hideActivity(this)

            toMainPage()
        } else {
            initObserver()

            mViewModel.config()
        }

        handleFCMData()
    }

    private fun initObserver() {
        mViewModel.configPreLiveData.observe(this) { response ->
            val resp = response.getSuccessResult()
            if (resp != null) {
                //判断更新
                val forceVersion = resp.forceVersion
                if (forceVersion != null) {
                    if (!forceVersion.promptOnlyOnce) {
                        CacheUtil.setUpdateVersion(forceVersion.buildVersion.toString(), false)
                    }
                    if (forceVersion.buildVersion > AppModule.getAppVersion() &&
                        !CacheUtil.getUpdateVersion(forceVersion.buildVersion.toString())
                    ) {
                        EventBus.getDefault().postSticky(AppVersionUpdateEvent(forceVersion))
                    }
                }
                gotoLogin()
            } else {
                //如果是停服
                if (response.code == CommonConst.ErrorCode.DISCONTINUED) {
                    val ext = (response.ext?.get("stopMessage") as? Map<String, Any>)?.let {
                        ReflexUtils.fromMap<DiscontinuedExt>(it)
                    }

                    toDiscontinued(ext)
                    return@observe
                }

                //如果小于1重试一次
                if (mRetryTimes < 1) {
                    mViewModel.config(true)
                } else {
                    keepScreen(false)

                    //否则直接弹窗，服务不可用
                    XPopup.Builder(this)
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .isDestroyOnDismiss(true)
                        .isViewMode(true)
                        .asCustom(
                            UniversalButtonDialog
                                .Builder(
                                    this,
                                    StringUtils.getString(string.server_failure)
                                )
                                .setConfirmText(StringUtils.getString(string.retry))
                                .setCancelText(StringUtils.getString(string.exit_app))
                                .setConfirmListener {
                                    mRetryTimes = 0

                                    mViewModel.config()
                                }
                                .setCancelListener {
                                    finish()
                                }
                                .build()
                        )
                        .show()
                }
                mRetryTimes++
            }
        }
    }

    private fun isMainTaskRunning(): Boolean {
        if (!isTaskRoot) {
            val intent = intent
            if (intent != null) {
                val action = intent.action
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                    return true
                }
            }
        }
        return false
    }

    private fun keepScreen(stay: Boolean) {
        mSplashScreen?.setKeepOnScreenCondition { stay }
    }

    private fun gotoLogin() {
        if (UserManager.isLogin()) {
            toMainPage()
        } else {
            toLoginPage()
        }
    }

    private fun toMainPage() {
        gotoAndCheck {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        }
    }

    //去选择登录
    private fun toLoginPage() {
        gotoAndCheck {
            Router.instance.setPath(RoutePath.LOGIN_ACTIVITY).navigation(this)
            finish()
        }
    }

    //退出App
    private fun toDiscontinued(ext: DiscontinuedExt?) {
        gotoAndCheck {
            if (ext != null) {
                Router.builder(RoutePath.DISCOUNTIUNED_ACTIVITY)
                    .withAny("data", ext).navigation(this)
            }
            finish()
        }
    }

    private fun gotoAndCheck(block: () -> Unit) {
        AdJustManager.checkDmaAndInit(this, block).apply {
            if (this) {
                keepScreen(false)
            }
        }
    }

    private fun handleFCMData() {
        val msgId = intent.extras?.getString("google.message_id")
        if (msgId != null) {
            val router = intent.extras?.getString("router")
            val router2 = intent.extras?.getString("router2")
            val content = intent.extras?.getString("ext")
            EventBus.getDefault().postSticky(FcmRouterEvent(router, router2, content))
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        NetworkUtils.unregisterNetworkStatusChangedListener(mNetStateListener)
    }
}